package com.qf.agro.web.interceptors;

import com.alibaba.fastjson.JSON;
import com.qf.agro.common.Constant;
import com.qf.agro.common.ResultInfo;
import com.qf.agro.common.SysUserHolder;
import com.qf.agro.pojo.SysUser;
import com.qf.agro.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ProjectName: smart-agriculture-parent
 * ClassName: CheckLoginInterceptor
 * Author: chenyaosen
 * Date: 2023/6/30 20:37
 * Description:
 */
@Component
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            ResultInfo resultInfo = ResultInfo.noLogin(Constant.NOT_LOGIN);
            String json = JSON.toJSONString(resultInfo);
            response.getWriter().write(json);
            return false;
        }
        try {
            Claims claims = jwtUtil.parseJWT(authorization);
            if (claims != null) {
                String id = claims.getId();
                String subject = claims.getSubject();
                SysUser sysUser = JSON.parseObject(subject, SysUser.class);
                if (sysUser != null) {
                    SysUserHolder.set(sysUser);
                    return true;
                }
            }
        } catch (Exception e) {
            ResultInfo resultInfo = ResultInfo.noLogin(Constant.NOT_LOGIN);
            String json = JSON.toJSONString(resultInfo);
            response.getWriter().write(json);
            return false;
        }
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SysUserHolder.remove();
    }
}
